02 新手必须掌握的 Linux 命令

强大好用的 SHELL

系统内核

用户与硬件

用户与硬件

Shell

Bash 解释器的优势

注意

Shell 与 Bash 是包含与被包含的关系。举例来说,在社会中有翻译官这个职业,它是由许多从业者共同组成的职业名称,而 Bash 则是其中一个出色的成员,是 Shell 终端程序中的一份子。

执行命令的必备知识

要想准确、高效地完成各种任务,仅依赖于命令本身是不够的,还应该根据实际情况来灵活调整各种命令的参数。

常见 Linux 命令的格式

命令名称   [命令参数]   [命令对象]
格式 示例
长格式 man --help
短格式 man -h
注意

  • 命令名称、命令参数与命令对象之间要用空格进行分隔,且字母严格区分大小写。
  • 在 Linux 系统中的命令参数有长短格式之分,长格式和长格式之间不能合并,长格式和短格式之间也不能合并,但短格式和短格式之间是可以合并的,合并后仅保留一个减号(-)即可。

在 RHEL 8 系统中执行 Linux 命令

img

注意

  • 命令名称、命令参数与命令对象之间要用空格进行分隔,且字母严格区分大小写。
  • 在输入命令前就已经存在的 [root@linuxprobe~]# 这部分内容是终端提示符,它用于向用户展示一些基本的信息。
    • 当前登录用户名为 root
    • 简要的主机名是 linuxprobe
    • 所在目录是 ~(这里的 ~ 是指用户家目录,第 6 章会讲解),# 表示管理员身份(如果是 $ 则表示普通用户,相应的权限也会小一些)。

man 命令中常用按键

man 命令中常用按键以及作用:

按键 作用
空格键 向下翻一页
PaGe down 向下翻一页
PaGe up 向上翻一页
home 直接前往首页
end 直接前往尾页
/ 从上至下搜索某个关键词,如 /linux
? 从下至上搜索某个关键词,如 ?linux
n 定位到下一个搜索到的关键词
N 定位到上一个搜索到的关键词
q 退出帮助文档

man 命令中帮助信息的结构

man 命令中帮助信息的结构以及意义:

结构名称 代表意义
NAME 命令的名称
SYNOPSIS 参数的大致使用方法
DESCRIPTION 介绍说明
EXAMPLES 演示(附带简单说明)
OVERVIEW 概述
DEFAULTS 默认的功能
OPTIONS 具体的可用选项(带介绍)
ENVIRONMENT 环境变量
FILES 用到的文件
SEE ALSO 相关的资料
HISTORY 维护历史与联系方式

额外快捷键/组合键小技巧

常用系统工作命令

Tip

  • 如果在系统终端中执行一个命令后想立即停止它,可以同时按下 Ctrl + C 组合键(生产环境中比较常用的一个组合键),这样将立即终止该命令的进程。
  • 如果有些命令在执行时不断地在屏幕上输出信息,影响到后续命令的输入,则可以在执行命令时在末尾添加一个 & 符号,这样命令将进入系统后台来执行。

echo

$ echo LinuxProbe.com
LinuxProbe.com
$ echo $SHELL
/bin/bash

date

$ date
Sat Sep 5 09:13:45 CST 2020

$ date "+%Y-%m-%d %H:%M:%S" # 按照 “年 - 月 - 日 小时: 分钟: 秒” 的格式查看
2020-09-05 09:14:35

$ date -s "20201101 8:30:00" # 将系统的当前时间设置为 2020 年 11 月 1 日 8 点 30 分
Sun Nov 1 08:30:00 CST 2020

$ date "+%j" #查看今天是当年中的第几天
306

timedatectl

$ timedatectl status
               Local time: Sun 2020-09-06 19:51:22 CST
           Universal time: Sun 2020-09-06 11:51:22 UTC
                 RTC time: Sun 2020-09-06 19:51:21
                Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: no
              NTP service: inactive
          RTC in local TZ: no

$ timedatectl set-timezone Asia/Shanghai # 手动设置时区是上海(Asia/Shanghai)
$ timedatectl set-time 2021-05-18 # 手动修改系统日期
$ timedatectl set-time 9:30 # 手动修改时间
$ date
Tue May 18 09:30:01 CST 2021

reboot

注意

由于重启计算机这种操作会涉及硬件资源的管理权限,因此最好是以 root 管理员的身份来重启,普通用户在执行该命令时可能会被拒绝。

poweroff

wget

$ wget https://www.linuxprobe.com/docs/LinuxProbe.pdf
--2020-09-28 19:24:39--  https://www.linuxprobe.com/docs/LinuxProbe.pdf
Resolving www.linuxprobe.com (www.linuxprobe.com)... 221.15.64.1
Connecting to www.linuxprobe.com (www.linuxprobe.com)|221.15.64.1|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17676281 (17M) [application/pdf]
Saving to: ‘LinuxProbe.pdf’

LinuxProbe.pdf      100%[===================>]  16.86M  15.9MB/s    in 1.1s

2020-09-28 19:24:40 (15.9 MB/s) - ‘LinuxProbe.pdf’ saved [17676281/17676281]

$ wget -r -p https://www.linuxprobe.com # 使用 wget 命令递归下载 www.linuxprobe.com 网站内的所有页面数据以及文件,下载完后会自动保存到当前路径下一个名为 www.linuxprobe.com 的目录中
--2020-09-28 19:26:12--  https://www.linuxprobe.com/
Resolving www.linuxprobe.com (www.linuxprobe.com)... 221.15.64.1
Connecting to www.linuxprobe.com (www.linuxprobe.com)|221.15.64.1|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘www.linuxprobe.com/index.html’
……………… 省略下载过程………………

ps

进程状态

Linux 系统中时刻运行着许多进程,如果能够合理地管理它们,则可以优化系统的性能。在 Linux 系统中有 5 种常见的进程状态,分别为运行、中断、不可中断、僵死与停止。

除了上面 5 种常见的进程状态,还有可能是高优先级(<)、低优先级(N)、被锁进内存(L)、包含子进程(s)以及多线程(l)这 5 种补充形式。

当执行 ps aux 命令后通常会看到如下表所示的进程状态。下表只是列举了部分输出值,而且正常的输出值中不包括中文注释。

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
进程的所有者 进程 ID 号 运算器占用率 内存占用率 虚拟内存使用量 (单位是 KB) 占用的固定内存量 (单位是 KB) 所在终端 进程状态 被启动的时间 实际使用 CPU 的时间 命令名称与参数
root 1 0.0 0.5 244740 10636 ? Ss 07:54 0:02 /usr/lib/systemd/ systemd --switched-root --system --deserialize 18
root 2 0.0 0.0 0 0 ? S 07:54 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? I< 07:54 0:00 [rcu_gp]
root 4 0.0 0.0 0 0 ? I< 07:54 0:00 [rcu_par_gp]
root 5 0.0 0.0 0 0 ? I< 07:54 0:00 [kworker/0:0H-kbl
root 6 0.0 0.0 0 0 ? I< 07:54 0:00 [mm_percpu_wq]
……………… 省略部分输出信息 ………………
注意

  • 在 Linux 系统中的命令参数有长短格式之分,长格式和长格式之间不能合并,长格式和短格式之间也不能合并,但短格式和短格式之间是可以合并的,合并后仅保留一个减号(-)即可。
  • ps 命令可允许参数不加减号(-),因此可直接写成 ps aux 的样子。

$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.6 179748 14048 ?        Ss   04:25   0:03 /usr/lib/systemd/systemd --switched-root --system --deserialize 18
root           2  0.0  0.0      0     0 ?        S    04:25   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        I<04:25   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I<04:25   0:00 [rcu_par_gp]
root           6  0.0  0.0      0     0 ?        I<04:25   0:00 [kworker/0:0H-kblockd]
root           8  0.0  0.0      0     0 ?        I<04:25   0:00 [mm_percpu_wq]
root           9  0.0  0.0      0     0 ?        S    04:25   0:00 [ksoftirqd/0]
linuxpr+    8553  0.0  0.2  24564  5032 pts/1    Ss   14:25   0:00 -bash
linuxpr+    8563  0.0  0.2  45848  5324 ?        Ss   14:25   0:00 /usr/libexec/openssh/sftp-server
root        8633  0.0  0.0   7280   724 ?        S    14:27   0:00 sleep 60
linuxpr+    8635  0.0  0.1  57820  4000 pts/1    R+   14:28   0:00 ps aux

pstree

$ pstree
systemd─┬─ModemManager───2*[{ModemManager}]
        ├─NetworkManager───2*[{NetworkManager}]
        ├─VGAuthService
        ├─accounts-daemon───2*[{accounts-daemon}]
        ├─alsactl
        ├─atd
        ├─auditd─┬─sedispatch
        │        └─2*[{auditd}]
        ├─avahi-daemon───avahi-daemon
        ├─boltd───2*[{boltd}]
        ├─colord───2*[{colord}]
……………… 省略部分输出信息………………

top

$ top
top - 14:29:47 up 10:04,  2 users,  load average: 0.00, 0.04, 0.05
Tasks: 319 total,   2 running, 317 sleeping,   0 stopped,   0 zombie
%Cpu(s):  1.0 us,  0.3 sy,  0.0 ni, 98.3 id,  0.0 wa,  0.3 hi,  0.0 si,  0.0 st
MiB Mem :   1960.0 total,    131.4 free,   1355.5 used,    473.2 buff/cache
MiB Swap:   2048.0 total,   2030.4 free,     17.6 used.    423.6 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
    992 root      20   0  309504  29824   9864 S   0.3   1.5   1:50.37 vmtoolsd
   2116 root      20   0  204924  32088  10164 S   0.3   1.6   0:54.69 sssd_kcm
   2338 linuxpr+  20   0  531720  34540  27668 S   0.3   1.7   1:45.38 vmtoolsd
   8547 linuxpr+  20   0  161180   6200   4880 S   0.3   0.3   0:00.02 sshd
      1 root      20   0  179748  14048   9184 S   0.0   0.7   0:03.40 systemd
      2 root      20   0       0      0      0 S   0.0   0.0   0:00.01 kthreadd
      3 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 rcu_gp
      4 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 rcu_par_gp
      6 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 kworker/0:0H-kblockd

nice

$ nice -n -20 bash # 将 bash 服务的优先级调整到最高

pidof

$ pidof sshd # 查询本机上 sshd 服务程序的 PID
2156

kill

$ pidof sshd
2156

$ kill 2156 # 强制停止 sshd 服务
$ kill -9 2156 # 最高级别地强制杀死进程

killall

$ pidof httpd # 查询 httpd 服务程序全部进程
5235 5233 5232 5231 5228

$ killall httpd  # 结束 httpd 服务程序全部进程
$ pidof httpd
$

系统状态检测命令

作为一名合格的运维人员,要想更快、更好地了解 Linux 服务器,必须具备快速查看系统运行状态的能力,因此接下来会逐个讲解与网卡网络、系统内核、系统负载、内存使用情况、当前启用终端数量、历史登录记录、命令执行记录以及救援诊断等相关命令的使用方法。

ifconfig

$ ifconfig
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.131  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::20c:29ff:fe99:f4b2  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:99:f4:b2  txqueuelen 1000  (Ethernet)
        RX packets 5442  bytes 547667 (534.8 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 9391  bytes 1781707 (1.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 72  bytes 6120 (5.9 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 72  bytes 6120 (5.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:d4:b1:9d  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

uname

$ uname -a
Linux linuxprobe.com 4.18.0-193.el8.x86_64 #1 SMP Fri Mar 27 14:35:58 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/redhat-release
Red Hat Enterprise Linux release 8.2 (Ootpa)

uptime

$ uptime
 14:31:55 up 10:06,  2 users,  load average: 0.00, 0.02, 0.03

free

$ free -h
              total        used        free      shared  buff/cache   available
Mem:          1.9Gi       1.3Gi       127Mi        21Mi       476Mi       422Mi
Swap:         2.0Gi        17Mi       2.0Gi

who

$ who
linuxprobe tty2         2023-06-04 04:26 (tty2)
linuxprobe pts/1        2023-06-04 14:25 (192.168.0.108)

last

$ last
linuxpro pts/1        192.168.0.108    Sun Jun  4 14:25   still logged in
linuxpro tty2         tty2             Sun Jun  4 04:26   still logged in
reboot   system boot  4.18.0-193.el8.x Sun Jun  4 04:26   still running
linuxpro tty2         tty2             Sun Jun  4 04:18 - down   (00:05)
reboot   system boot  4.18.0-193.el8.x Sun Jun  4 04:18 - 04:24  (00:06)
linuxpro tty2         tty2             Sun Jun  4 03:26 - crash  (00:51)
reboot   system boot  4.18.0-193.el8.x Sun Jun  4 03:18 - 04:24  (01:06)

wtmp begins Sun Jun  4 03:18:13 2023

ping

$ ping 192.168.0.108 # 测试主机
PING 192.168.0.108 (192.168.0.108) 56(84) bytes of data.
64 bytes from 192.168.0.108: icmp_seq=1 ttl=64 time=0.404 ms
64 bytes from 192.168.0.108: icmp_seq=2 ttl=64 time=0.729 ms
64 bytes from 192.168.0.108: icmp_seq=3 ttl=64 time=1.08 ms
64 bytes from 192.168.0.108: icmp_seq=4 ttl=64 time=0.688 ms
64 bytes from 192.168.0.108: icmp_seq=5 ttl=64 time=0.730 ms{ #C}

--- 192.168.0.108 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 16ms
rtt min/avg/max/mdev = 0.404/0.726/1.080/0.215 ms

$ ping 192.168.0.40 # 测试一台不在线的主机
PING 192.168.0.40 (192.168.0.40) 56(84) bytes of data.
From 192.168.0.131 icmp_seq=1 Destination Host Unreachable
From 192.168.0.131 icmp_seq=2 Destination Host Unreachable
From 192.168.0.131 icmp_seq=3 Destination Host Unreachable
From 192.168.0.131 icmp_seq=4 Destination Host Unreachable
From 192.168.0.131 icmp_seq=5 Destination Host Unreachable
From 192.168.0.131 icmp_seq=6 Destination Host Unreachable{ #C}

--- 192.168.0.40 ping statistics ---
7 packets transmitted, 0 received, +6 errors, 100% packet loss, time 189ms
pipe 4

tracepath

$ tracepath www.linuxprobe.com
 1?: [LOCALHOST]                      pmtu 1500
 1:  _gateway                                              2.458ms
 1:  _gateway                                              2.648ms
 2:  192.168.1.1                                           3.286ms
 3:  192.168.1.1                                           2.825ms pmtu 1480
 3:  10.0.144.1                                           12.397ms
 4:  123.139.1.41                                          5.313ms
 5:  221.11.0.97                                          21.903ms asymm  8
 6:  221.11.0.25                                          34.017ms asymm  8
……………… 省略部分输出信息………………

netstat

$ netstat -a # 显示详细的网络状况
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN
tcp        0      0 linuxprobe.com:domain   0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp        0      0 localhost:ipp           0.0.0.0:*               LISTEN
……………… 省略部分输出信息………………

$ netstat -i # 显示网卡列表
Kernel Interface table
Iface             MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
ens160           1500     5940      0      0 0          9778      0      0      0 BMRU
lo              65536       79      0      0 0            79      0      0      0 LRU
virbr0           1500        0      0      0 0             0      0      0      0 BMU

history

$ history
    1  ifconfig
    2  cat /etc/sysconfig/network-scripts/ifcfg-ens160
    3  vi /etc/sysconfig/network-scripts/ifcfg-ens160
    4  sudo vi /etc/sysconfig/network-scripts/ifcfg-ens160
    5  su - root
    6  uname -a
    7  ps aux
    8  pstree
    9  top
   10  clear
   11  ifconfig
   12  uname -a
   13  cat /etc/redhat-release
   14  uptime
   15  clear
   16  free -h
   17  who
   18  last
   19  ping www.baidu.com
   20  ping google.com
   21  ping 192.168.0.108
   22  ping 192.168.0.40
   23  clear
   24  tracepath www.linuxprobe.com
   25  netstat -a
   26  netstat -i
   27  history

$ !17
who
linuxprobe tty2         2023-06-04 04:26 (tty2)
linuxprobe pts/1        2023-06-04 14:25 (192.168.0.108)

$ history -c # 清空所有的命令历史记录
$ history
    1  history

sosreport

$ sosreport
sosreport (version 3.6)
This command will collect diagnostic and configuration information from
this Red Hat Enterprise Linux system and installed applications.

An archive containing the collected information will be generated in
/var/tmp/sos.9_i0glu8 and may be provided to a Red Hat support
representative.

Any information provided to Red Hat will be treated in accordance with
the published support policies at:
https://access.redhat.com/support/
The generated archive may contain data considered sensitive and its
content should be reviewed by the originating organization before being
passed to any third party.

No changes will be made to system configuration.
Press ENTER to continue, or CTRL-C to quit.
此处按下回车键进行确认
Please enter the case id that you are generating this report for []: 此处按下回车键进行确认
Setting up archive ...
Setting up plugins ...
Running plugins. Please wait ...
……………… 省略部分输出信息………………
Finished running plugins
Creating compressed archive...

Your sosreport has been generated and saved in:
/var/tmp/sosreport-linuxprobe.com-2021-05-18-jnkaspu.tar.xz

The checksum is: 9fbecbd167b7e5836db1ff8f068c4db3
Please send this file to your support representative.

查找定位文件命令

工作目录指的是用户当前在系统中所处的位置。由于工作目录会牵涉系统存储结构相关的知识,因此第 6 章将详细讲解这部分内容。

pwd

pwd 命令用于显示用户当前所处的工作目录,英文全称为 "print working directory",输入该命令后按回车键执行即可。

$ pwd # 查看当前所处的工作目录
/etc

cd

$ cd /etc # 切换进 /etc 目录中
$ cd /bin # 切换到 /bin 目录
$ cd - # 返回到上一次的目录(即 /etc 目录)
$ cd ~ # 快速切换到用户的家目录

ls

$ ls -al
total 48
dr-xr-x---. 15 root root 4096 Jul 24 06:33 .
dr-xr-xr-x. 17 root root  224 Jul 21 05:04 ..
-rw-------.  1 root root 1407 Jul 21 05:09 anaconda-ks.cfg
-rw-------.  1 root root  335 Jul 24 06:33 .bash_history
-rw-r--r--.  1 root root   18 Aug 13  2018 .bash_logout
-rw-r--r--.  1 root root  176 Aug 13  2018 .bash_profile
-rw-r--r--.  1 root root  176 Aug 13  2018 .bashrc
-rw-------.  1 root root 3235 Jul 24 06:32 .viminfo

$ ls -ld /etc # 查看 /etc 目录的权限与属性信息
drwxr-xr-x. 132 root root 8192 Jul 10 10:48 /etc

tree

find

$ find /etc -name "host*" -print # 获取该目录中所有以 host 开头的文件列表
/etc/host.conf
/etc/hosts
/etc/hosts.allow
/etc/hosts.deny
/etc/avahi/hosts
/etc/hostname

$ find / -perm -4000 -print # 在整个系统中搜索权限中包括 SUID 权限的所有文件
/usr/bin/fusermount
/usr/bin/chage
/usr/bin/gpasswd
/usr/bin/newgrp
/usr/bin/umount
/usr/bin/mount
……………… 省略部分输出信息………………

$ find / -user linuxprobe -exec cp -a {} /root/findresults/ \; # 在整个文件系统中找出所有归属于 linuxprobe 用户的文件并复制到 /root/findresults 目录中。

locate

$ updatedb
$ ls -l /var/lib/mlocate/mlocate.db
-rw-r-----. 1 root slocate 2945917 Sep 13 17:54 /var/lib/mlocate/mlocate.db

$ locate whereis # 搜索出所有包含 “whereis” 名称的文件所在的位置
/usr/bin/whereis
/usr/share/bash-completion/completions/whereis
/usr/share/man/man1/whereis.1.gz

whereis

$ whereis ls
ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz

$ whereis pwd
pwd: /usr/bin/pwd /usr/share/man/man1/pwd.1.gz /usr/share/man/man1p/pwd.1p.gz

which

$ which locate
/usr/bin/locate

$ which whereis
/usr/bin/whereis

文本文件编辑命令

在 Linux 系统中,一切都是文件,对服务程序进行配置自然也就是编辑程序的配置文件。如果不能熟练地查阅系统或服务的配置文件,那以后工作时可就真的要尴尬了。本节将讲解几条用于查看文本文件内容的命令。至于相对比较复杂的文本编辑器工具,将在第 4 章与 Shell 脚本一起讲解。

cat

$ cat -n .bashrc
     1  # .bashrc
     2
     3  # Source global definitions
     4  if [-f /etc/bashrc]; then
     5          . /etc/bashrc
     6  fi
     7
     8  # User specific environment
     9  PATH="$HOME/.local/bin:$HOME/bin:$PATH"
    10  export PATH
    11
    12  # Uncomment the following line if you don't like systemctl's auto-paging feature:
    13  # export SYSTEMD_PAGER=
    14
    15  # User specific aliases and functions

more

$ more initial-setup-ks.cfg
#version=RHEL8
# X Window System configuration information
xconfig  --startxonboot
# License agreement
eula --agreed
# Use graphical install
--More--(20%)
$ head -n 6 initial-setup-ks.cfg
#version=RHEL8
# X Window System configuration information
xconfig --startxonboot
# License agreement
eula --agreed
# Use graphical install

tail

$ tail -n 6 initial-setup-ks.cfg

%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end

$ tail -f /var/log/messages
Sep 15 00:14:06 localhost systemd[1]: Starting SSSD Kerberos Cache Manager...
Sep 15 00:14:06 localhost systemd[1]: Started SSSD Kerberos Cache Manager.
Sep 15 00:14:06 localhost sssd[kcm][3989]: Starting up
Sep 15 00:14:26 localhost NetworkManager[1203]: <info> [1600100066.4675] audit: op="sleep-control" arg="off" pid=3990 uid=0 result="fail" reason="Already awake"
Sep 15 00:19:04 localhost org.gnome.Shell.desktop[2600]: Window manager warning: last_user_time (2361102) is greater than comparison timestamp (2361091). This most likely represents a buggy client sending inaccurate timestamps in messages such as _NET_ACTIVE_WINDOW. Trying to work around...
Sep 15 00:19:04 localhost org.gnome.Shell.desktop[2600]: Window manager warning: W14 (root@local) appears to be one of the offending windows with a timestamp of 2361102. Working around...

tr

$ tr [a-z] [A-Z] < File.cfg  # cat File.cfg | tr [a-z] [A-Z] # 将指定文件中的小写字母转换成大写字母后输出内容到终端界面
#VERSION=RHEL8
IGNOREDISK --ONLY-USE=SDA
AUTOPART --TYPE=LVM
# PARTITION CLEARING INFORMATION
CLEARPART --ALL --INITLABEL --DRIVES=SDA
# USE GRAPHICAL INSTALL
……………… 省略部分输出信息………………

$ tr -d [0-9] < File.cfg # 删除指定文件中所有的数字后输出内容到终端界面
#version=RHEL
ignoredisk --only-use=sda
autopart --type=lvm
# Partition clearing information
clearpart --all --initlabel --drives=sda
# Use graphical install
……………… 省略部分输出信息………………

$ tr -s "[\n]" < File.cfg  # 将指定文件中的多个相邻空行去重后输出内容到终端界面
#version=RHEL8
ignoredisk --only-use=sda
autopart --type=lvm
# Partition clearing information
clearpart --all --initlabel --drives=sda
# Use graphical install
……………… 省略部分输出信息………………

wc

$ wc -l /etc/passwd
45 /etc/passwd
Info

在 Linux 系统中,/etc/passwd 是用于保存所有用户信息的文件,要统计当前系统中有多少个用户,可以使用 wc -l /etc/passwd 命令来进行查询。

stat

$ stat anaconda-ks.cfg
  File: anaconda-ks.cfg
  Size: 1407      	Blocks: 8          IO Block: 4096   regular file
Device: fd00h/64768d	Inode: 35321091    Links: 1
Access: (0600/-rw-------)  Uid: (    0/    root)   Gid: (    0/    root)
Context: system_u:object_r:admin_home_t:s0
Access: 2020-07-21 05:16:52.347279499 +0800
Modify: 2020-07-21 05:09:16.421009316 +0800
Change: 2020-07-21 05:09:16.421009316 +0800
 Birth: -

grep

# 在 Linux 系统中,/etc/passwd 文件保存着所有的用户信息,而一旦用户的登录终端被设置成 /sbin/nologin,则不再允许登录系统,
# 因此可以使用 grep 命令查找出当前系统中不允许登录系统的所有用户的信息
$ grep /sbin/nologin /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin

cut

$ cut -d : -f 1 /etc/passwd # 以冒号为间隔符,仅提取指定文件中第一列的内容
root
bin
daemon
adm
lp
sync
……………… 省略部分输出信息………………

$ cut -c 1-4 /etc/passwd # 提取指定文件中每行的前 4 个字符
root
bin:
daem
adm:
lp:x
sync
……………… 省略部分输出信息………………

diff

# 先使用 cat 命令分别查看 diff_A.txt 和 diff_B.txt 文件的内容,然后进行比较
$ cat diff_A.txt
Welcome to linuxprobe.com
Red Hat certified
Free Linux Lessons
Professional guidance
Linux Course

$ cat diff_B.txt
Welcome tooo linuxprobe.com

Red Hat certified
Free Linux LeSSonS
////////.....////////
Professional guidance
Linux Course

# 使用 diff --brief 命令显示比较后的结果,判断文件是否相同
$ diff --brief diff_A.txt diff_B.txt
Files diff_A.txt and diff_B.txt differ

# 使用带有 -c 参数的 diff 命令来描述文件内容具体的不同
$ diff -c diff_A.txt diff_B.txt
*** diff_A.txt 2020-08-30 18:07:45.230864626 +0800
--- diff_B.txt 2020-08-30 18:08:52.203860389 +0800
***************
*** 1,5 ****
! Welcome to linuxprobe.com
Red Hat certified
! Free Linux Lessons
Professional guidance
Linux Course
--- 1,7 ----
! Welcome tooo linuxprobe.com
!
Red Hat certified
! Free Linux LeSSonS
! ////////.....////////
Professional guidance
Linux Course

uniq

$ cat uniq.txt
Welcome to linuxprobe.com
Welcome to linuxprobe.com
Welcome to linuxprobe.com
Welcome to linuxprobe.com
Red Hat certified
Free Linux Lessons
Professional guidance
Linux Course

$ uniq uniq.txt
Welcome to linuxprobe.com
Red Hat certified
Free Linux Lessons
Professional guidance
Linux Course

sort

# 执行 sort 命令后默认会按照字母顺序进行排序
$ cat fruit.txt
banana
pear
apple
orange
raspaberry

$ sort fruit.txt
apple
banana
orange
pear
raspaberry

# 按照 user.txt 文件中的第 3 列进行数值排序,列之间使用 “:” 作为分隔符
$ cat user.txt
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon
polkitd:x:998:996:User for polkitd
geoclue:x:997:995:User for geoclue
rtkit:x:172:172:RealtimeKit
pulse:x:171:171:PulseAudio System Daemon
qemu:x:107:107:qemu user
usbmuxd:x:113:113:usbmuxd user
unbound:x:996:991:Unbound DNS resolver
rpc:x:32:32:Rpcbind Daemon
gluster:x:995:990:GlusterFS daemons

# -t 参数指定分隔符为 “:”,-k 参数指定按第几列排序(这里是第 3 列),-n 参数指定按照数值排序。
$ sort -t : -k 3 -n user.txt
rpc:x:32:32:Rpcbind Daemon
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon
qemu:x:107:107:qemu user
usbmuxd:x:113:113:usbmuxd user
pulse:x:171:171:PulseAudio System Daemon
rtkit:x:172:172:RealtimeKit
gluster:x:995:990:GlusterFS daemons
unbound:x:996:991:Unbound DNS resolver
geoclue:x:997:995:User for geoclue
polkitd:x:998:996:User for polkitd
sort Vs uniq

uniq 命令不同,sort 命令是无论内容行之间是否夹杂有其他内容,只要有两个一模一样的内容行,立马就可以使用 -u 参数进行去重操作。

$ cat -n urls.txt
   1  Welcome to linuxprobe.com
   2  Red Hat certified
   3  Welcome to linuxprobe.com
   4  Free Linux Lessons
   5  Linux Course%

$ sort -u urls.txt
Free Linux Lessons
Linux Course
Red Hat certified
Welcome to linuxprobe.com

$ uniq urls.txt
Welcome to linuxprobe.com
Red Hat certified
Welcome to linuxprobe.com
Free Linux Lessons
Linux Course

文件目录管理命令

有了上面的知识铺垫,我们将在本节介绍 Linux 系统日常运维工作中最常用的命令,实现对文件的创建、修改、复制、剪切、更名与删除等操作。

touch

# 先使用 ls 命令查看一个文件的修改时间,随后修改这个文件,最后再查看一下文件的修改时间,看是否发生了变化、
$ ls -l anaconda-ks.cfg
-rw-------. 1 root root 1213 May  4 15:44 anaconda-ks.cfg
$ echo "Visit the LinuxProbe.com to learn linux skills" >> anaconda-ks.cfg
$ ls -l anaconda-ks.cfg
-rw-------. 1 root root 1260 Aug  2 01:26 anaconda-ks.cfg

# 如果不想让别人知道我们修改了它,那么这时就可以用 touch 命令把修改后的文件时间设置成修改之前的时间
$ touch -d "2020-05-04 15:44" anaconda-ks.cfg
$ ls -l anaconda-ks.cfg
-rw-------. 1 root root 1260 May  4 15:44 anaconda-ks.cfg

mkdir

$ mkdir linuxprobe
$ cd linuxprobe
$ mkdir -p a/b/c/d/e
$ cd a
$ cd b
$

cp

# 使用 touch 命令创建一个名为 install.log 的普通空白文件,然后将其复制为一份名为 x.log 的备份文件,最后再使用 ls 命令查看目录中的文件
$ touch install.log
$ cp install.log x.log
$ ls
install.log x.log

mv

$ mv x.log linux.log
$ ls
install.log linux.log

rm

# 尝试删除前面创建的 install.log 和 linux.log 文件,大家感受一下加与不加 -f 参数的区别
[root@linuxprobe ~]# rm install.log
rm: remove regular empty file ‘install.log’? y
[root@linuxprobe ~]# rm -f linux.log
[root@linuxprobe ~]# ls
[root@linuxprobe ~]#

dd

# 用 dd 命令从 /dev/zero 设备文件中取出一个大小为 560MB 的数据块,然后保存成名为 560_file 的文件。
[root@linuxprobe ~]# dd if=/dev/zero of=560_file count=1 bs=560M
1+0 records in
1+0 records out
587202560 bytes (587 MB, 560 MiB) copied, 1.28667 s, 456 MB/s

# 使用 dd 命令来压制出光盘镜像文件,将它变成一个可立即使用的 iso 镜像
[root@linuxprobe ~]# dd if=/dev/cdrom of=RHEL-server-8.0-x86_64-LinuxProbe.Com.iso
13873152+0 records in
13873152+0 records out
7103053824 bytes (7.1 GB, 6.6 GiB) copied, 27.8812 s, 255 MB/s
bs 块大小与 count 块个数的关系

  • 假设小明的饭量(即需求)是一个固定的值,用来盛饭的勺子的大小是 bs 块的大小,而用勺子盛饭的次数则是 count 块的个数。
  • 小明要想吃饱(满足需求),则需要在勺子大小(bs 块大小)与用勺子盛饭的次数(count 块个数)之间进行平衡。勺子越大,用勺子盛饭的次数就越少。
  • 由上可见,bs 与 count 都是用来指定容量的大小,只要能满足需求,可随意组合搭配方式。

file

[root@linuxprobe ~]# file anaconda-ks.cfg
anaconda-ks.cfg: ASCII text
[root@linuxprobe ~]# file /dev/sda
/dev/sda: block special
Info

  • 在 Windows 系统中打开文件时,一般是通过用户双击鼠标完成的,系统会自行判断用户双击的文件是什么类型,因此需要有后缀进行区别。
  • Linux 系统则是根据用户执行的命令来调用文件,例如执行 cat 命令查看文本,执行 bash 命令执行脚本等,所以也就不需要强制让用户给文件设置后缀了。

tar

# 使用 tar 命令把 /etc 目录通过 gzip 格式进行打包压缩,并把文件命名为 etc.tar.gz
[root@linuxprobe ~]# tar czvf etc.tar.gz /etc
tar: Removing leading `/' from member names
/etc/
/etc/fstab
/etc/crypttab
/etc/mtab
/etc/fonts/
/etc/fonts/conf.d/
……………… 省略部分压缩过程信息………………

# 将打包后的压缩包文件指定解压到 /root/etc 目录中(先使用 mkdir 命令创建 /root/etc 目录):
[root@linuxprobe ~]# mkdir /root/etc
[root@linuxprobe ~]# tar xzvf etc.tar.gz -C /root/etc
etc/
etc/fstab
etc/crypttab
etc/mtab
etc/fonts/
etc/fonts/conf.d/
……………… 省略部分解压过程信息………………

总结